package com.xiaoxu.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoxu.auth.mapper.SysRoleMapper;
import com.xiaoxu.auth.mapper.SysUserRoleMapper;
import com.xiaoxu.auth.service.SysRoleService;
import com.xiaoxu.auth.service.SysUserRoleService;
import com.xiaoxu.model.system.SysRole;
import com.xiaoxu.model.system.SysUserRole;
import com.xiaoxu.vo.system.AssginRoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@Repository
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
    @Autowired
    private SysUserRoleService sysUserRoleService;



    @Override
    public Map<String, Object> findRoleByAdminId(Long userId) {
        //查询所有的角色
        List<SysRole> allRolesList = baseMapper.selectList(null);

        //拥有的角色id
       LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
       wrapper.eq(SysUserRole::getUserId,userId);
        List<SysUserRole> existRoleList = sysUserRoleService.list(wrapper);

        List<Long> existRoleIDList = existRoleList.stream().map(c -> c.getRoleId()).collect(Collectors.toList());


        //对角色进行分类
        List<SysRole> assginRoleList = new ArrayList<>();
        for (SysRole role : allRolesList) {
            //已分配
            if(existRoleIDList.contains(role.getId())) {
                assginRoleList.add(role);
            }
        }

        Map<String, Object> roleMap = new HashMap<>();
        roleMap.put("assginRoleList", assginRoleList);
        roleMap.put("allRolesList", allRolesList);
        return roleMap;

    }

    @Override
    public void doAssign(AssginRoleVo assginRoleVo) {
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId,assginRoleVo.getUserId());
        sysUserRoleService.remove(wrapper);
        //重新分配
        List<Long> roleIdList = assginRoleVo.getRoleIdList();
        for(Long roleId : roleIdList) {
            if(StringUtils.isEmpty(roleId)) continue;
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(assginRoleVo.getUserId());
            userRole.setRoleId(roleId);
            sysUserRoleService.save(userRole);
        }
    }
}
